from rest_framework import serializers

# 添加购物车序列化器
from goods.models import SKU


class CartSerializers(serializers.Serializer):
    sku_id = serializers.IntegerField(min_value=1)
    count = serializers.IntegerField(min_value=1)
    selected = serializers.BooleanField(default=True)

    # 判断商品是否存在
    def validate(self, attrs):
        try:
            sku = SKU.objects.get(id=attrs['sku_id'])
        except:
            raise serializers.ValidationError('该商品不存在')

        # 验证库存
        if attrs['count'] > sku.stock:
            raise serializers.ValidationError('该商品库存不足')

        return attrs

    # 获取商品数据


class CartsSerializers(serializers.ModelSerializer):
    count = serializers.IntegerField(read_only=True)
    selected = serializers.IntegerField(read_only=True)

    class Meta:
        model = SKU
        fields = '__all__'


# 定义个删除商品的序列化器
class CartDeleteSerializers(serializers.Serializer):
    sku_id = serializers.IntegerField(min_value=1)

    # 判断商品是否存在
    def validate(self, attrs):
        try:
            sku = SKU.objects.get(id=attrs['sku_id'])
        except:
            raise serializers.ValidationError('该商品不存在')
        return attrs

# 定义一个全选状态的序列化器
class CartSelectionSerializers(serializers.Serializer):
    selected = serializers.BooleanField(write_only=True)